<?php

namespace App\Http\Controllers\Api;

use App\Exceptions\ResponseException;
use App\Http\Requests\Api\Comment\CommentRequest;
use App\Models\Article;
use App\Models\Comment;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;

class CommentController extends Controller
{

	/**
	 * 发布留言
	 * User: Clannad ~ ☆
	 * DateTime: 2019/11/2 12:12
	 * @param Request $request
	 */
	public function store(CommentRequest $request, Comment $commentModel, $id)
	{
		//查询文章是否存在
		$article = Article::find($id);
		if ( ! $article) {
			throw new ResponseException(404, '文章不存在');
		}

		$user_id = auth('api')->id();

		$commentData = [
			'reply_user_id' => $request->input('reply_user_id') ?? 0,
			'pid'           => $request->input('pid') ?? 0,
			'content'       => $request->input('content'),
		];

		$commentModel->fill($commentData);
		$commentModel->user_id = $user_id;
		$comment               = $article->comment()->save($commentModel);

		if ($comment->id) {
			//用模型事件 给文章评论数+1
			throw new ResponseException(200, '评论成功，请等待管理员审核');
		} else {
			throw new ResponseException(500, '评论失败，请稍后再试');
		}
	}


	/**
	 * 删除留言
	 * User: Clannad ~ ☆
	 * DateTime: 2019/11/2 12:12
	 * @param $id
	 */
	public function destroy($id)
	{
		$comment = Comment::find($id);

		if(! $comment){
			throw new ResponseException(404,'留言不存在');
		}

		//判断留言用户是否为当前用户
		$user_id = auth('api')->id();
		if($comment->user_id != $user_id){
			throw new ResponseException(403,'只能删除自己的留言');
		}

		$comment->delete($id);

		throw new ResponseException(200,'删除成功');
	}
}
